<?php
/**
 * User: 269995848@qq.com
 * Date: 2019/3/3 18:36
 */

namespace app\qqbot\service\behavior\achieve;

use app\lib\enum\Code;
use app\lib\enum\QqBot;
use app\qqbot\service\event;
use app\qqbot\service\extend\ChangeCommand;
use app\qqbot\service\myservice\SendMessage;
use app\qqbot\service\src\Config;
use app\qqbot\service\src\CQCode;
use think\facade\Cache;


class MessageRoute{

    protected $event;

    public function __construct(array $event=[]){
        $this->event=$event;
    }


    public function index(){
        switch($this->event['post_type']){
            case "message":
                return (new Message())->route($this->event);
            case "notice" :
                return (new Notice())->route($this->event);
            case "request":
                return (new Request())->route($this->event);
            default :
                return event\SendMessageEvent::sendMaster('Unknown post type, Event:'."\n".var_export($_SERVER,true),$this->event['agent_id']);
        }
    }

    protected function isPrefix(array $event){
        $message=trim($event['message']);

        if(("帮助" == $message) | ("!帮助" == $message)){
            $arr['command']="help";
            return $this->loadCommand($arr,$event);
        }

        file_put_contents('./success.txt','====1=====',8);

        //玩法解析
        if(redisObj()->get(Code::STOP_BETTING)){
            $arr['command']="rule";
            $res=$this->loadCommand($arr,$event);
            if(is_array($res) | is_object($res)){
                file_put_contents('./success.txt','====2=====',8);
                return $res;
            }
        }


        if($prefixCommand=redisObj()->get(QqBot::PREFIX_COMMAND)){
            if(preg_match('/^('.$prefixCommand.')/',$message,$command)){
                $command=trim(substr($message,strpos($message,$prefixCommand)+1,strlen($message)));
                $command=ChangeCommand::parseCommand($command);
                return $this->loadCommand($command,$event);
            }else{//未匹配前缀，代表不是命令,如果需要提示，请自行编写业务
                die("不是命令,我不会去识别");
            }
        }else{    //如果关闭前缀则需要识别所有的消息
            return $this->loadCommand(ChangeCommand::parseCommand($message),$event);
        }
    }

    protected function loadCommand(array $command,array $event){
        $class='\app\qqbot\service\command\\'.ucfirst($command['command']);

        try{
            if(isset($command['rule']) && $command['rule']){
                return (new $class)->index($event,$command['rule']);
            }else{
                return (new $class)->index($event,false);
            }

        }catch(\Throwable  $e){
            return event\SendMessageEvent::sendBack(CQCode::At($event['user_id']).QqBot::RESOLUTION_M,$event);
        }
    }


}